package com.hzit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzit.entity.User;
import com.hzit.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 1. 在此接口的方法中定义用户认证逻辑
 */
@Service
public class HzitUserDetailService implements UserDetailsService {
	@Autowired
	private IUserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//1. 根据用户名查询出用户
		User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
		if(user == null){
			throw new UsernameNotFoundException("用户名或密码不正确!");
		}
		//2. 得到用户名关联的密码
		String password = user.getPassword();
		//3. 自带义权限串，模拟数据库的权限串
		List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,user,haha,ROLE_user,ROLE_haha");
		return new org.springframework.security.core.userdetails.User(username,password,authorities);
	}

	public static void main(String[] args) {
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		String encode = passwordEncoder.encode("123");
		System.out.println("encode = " + encode);
	}
}
